package cn.clwxy.gdz.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.clwxy.gdz.entity.Student;
import cn.clwxy.gdz.entity.Teacher;
import cn.clwxy.gdz.service.LoginService;
import cn.clwxy.gdz.service.LoginServiceImpl;
import cn.clwxy.gdz.util.JsonSerializeHelper;
import cn.clwxy.gdz.util.MD5Encrypter;

/**
 * Servlet implementation class Login
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		String login_phone = request.getParameter("login_phone");
		String login_pwd = request.getParameter("login_pwd");
		System.out.println(login_pwd);
		
		
		
		login_pwd=login_phone+login_pwd+login_phone;
		login_pwd = MD5Encrypter.encrypt(login_pwd);
		
		
		
		
		
		System.out.println(login_pwd);
		LoginService loginService = new LoginServiceImpl();
		HttpSession session=request.getSession();
		try {
			if (loginService.isStudent(login_phone)) {
				System.out.println("ѧ���¼");
				Student student = loginService.getStudent(login_phone, login_pwd);
				System.out.println(student);
				session.setAttribute("type", 1);
				session.setAttribute("name", student.getStudentName());
				session.setAttribute("id", student.getStudentId());
				String json = JsonSerializeHelper.JsonSerializer(student);
				response.getWriter().write(json);
			}else if("admin".equals(login_phone)&&"ff85952a1e7942b6abcd43c622e47581".equals(login_pwd)){
				System.out.println("����Ա��¼");
				session.setAttribute("type", 3);
				String json = JsonSerializeHelper.JsonSerializer(3);
				response.getWriter().write(json);
			}else if(loginService.isTeacher(login_phone)){
				System.out.println("��ʦ��¼");
				Teacher teacher=loginService.getTeaher(login_phone, login_pwd);
				System.out.println(teacher);
				session.setAttribute("id", teacher.getId());
				session.setAttribute("type", 2);
				session.setAttribute("name", teacher.getRealName());
				String json = JsonSerializeHelper.JsonSerializer(teacher);
				response.getWriter().write(json);
			}else{
				response.getWriter().write(JsonSerializeHelper.JsonSerializer(""));
				System.out.println("��¼ʧ��");
			}
		} catch (Exception e) {
			response.getWriter().write(JsonSerializeHelper.JsonSerializer(""));
			e.printStackTrace();
		}
	}
}
